package com.wewins.fota.controller;

import com.alibaba.fastjson.JSONObject;
import com.wewins.fota.aop.Operator;
import com.wewins.fota.bean.dto.CheckStatusReq;
import com.wewins.fota.bean.dto.CheckStatusResp;
import com.wewins.fota.bean.dto.ResponseRst;
import com.wewins.fota.common.constant.FotaCode;
import com.wewins.fota.common.constant.HttpConst;
import com.wewins.fota.common.util.CommonUtil;
import com.wewins.fota.service.PlanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Slf4j
@Controller
public class PublicServeController {
    private final PlanService planService;

    @Autowired
    public PublicServeController(PlanService planService) {
        this.planService = planService;
    }

    @GetMapping("/version/query")
    @ResponseBody
    @Operator(FotaCode.CMD_VERSION_QUERY)
    public void checkStatus(HttpServletRequest request, HttpServletResponse response, @RequestParam Map<String, String> params) throws IOException {
        CheckStatusReq checkStatusReq = CheckStatusReq.builder().params(params).build();
        BindingResult result = checkStatusReq.check();
        if (result != null) {
            JSONObject.writeJSONString(response.getWriter(), ResponseRst.<List<String>>builder()
                    .data(CommonUtil.getRstStrings(result))
                    .build()
                    .withDefaultError(HttpConst.MSG_FAIL_BIND_PARAM_EXCEPTION));
            return;
        }
        CheckStatusResp data = planService.checkStatus(request, checkStatusReq);
        if (data == null) {
            JSONObject.writeJSONString(response.getWriter(), CheckStatusResp.builder().build());
        } else {
            JSONObject.writeJSONString(response.getWriter(), data.expandDownloadUrl(checkStatusReq));
        }
    }
}
